package com.jqb.jspcart.servlet;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jqb.jspcart.bean.Hardware;
import com.jqb.jspcart.service.impl.HardwareServiceImpl;

public class HardwareServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req,resp);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String opt = request.getParameter("opt");
		String str2 = request.getParameter("pageNum");
		String sort = request.getParameter("sort");
		ArrayList<String> hardwareSort = null;
		ArrayList<Hardware> hardwareList = null;
		//分页参数
		int sum = 0;
		sort=(sort==null)?"显卡":sort;
		try {
			sum = HardwareServiceImpl.newInstance().getHardwareCount(sort);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		int pageSize = 4;
		int pageNum = 1;
		int pageCount = (sum-1)/pageSize+1;
		
		pageNum=(str2==null)?1:Integer.parseInt(str2);
		
		if(pageNum<=0 || pageNum>pageCount){
			pageNum = 1;
		}
		
		//显示所有分类
		if(opt.equals("list")){
			try {
				hardwareSort = HardwareServiceImpl.newInstance().getHardwareSort();
				hardwareList = HardwareServiceImpl.newInstance().getHardwareList(4, 1, sort);
			} catch (Exception e) {
				e.printStackTrace();
			}
			request.setAttribute("pageCount", pageCount);
			request.setAttribute("pageNum", pageNum);
			request.setAttribute("hardwareList", hardwareList);
			request.setAttribute("sort", sort);
			request.getSession().setAttribute("hardwareSort", hardwareSort);
			request.getRequestDispatcher("hardwarelist.jsp").forward(request, response);
		}
		//显示各种硬件列表
		if(opt.equals("sort")){
			try {
				hardwareList = HardwareServiceImpl.newInstance().getHardwareList(pageSize, pageNum, sort);
			} catch (SQLException e) {
				e.printStackTrace();
			}
			if(hardwareList.size()>0){
				request.setAttribute("pageCount", pageCount);
				request.setAttribute("pageNum", pageNum);
				request.setAttribute("sort", sort);
				request.setAttribute("hardwareList", hardwareList);
				request.getRequestDispatcher("hardwarelist.jsp").forward(request, response);
			}
		}
	}
	
}
